package tree.test129;

import listbyorder.utils.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/7/17 10:09
 */
public class Solution2 {

    // 方法二 ； 遍历出来
    // 思路： 将所有根节点到叶子节点的路径遍历出来，然后累加
    List<String> temp = new ArrayList<>();

    public int sumNumbers(TreeNode root) {
        if (root == null) return 0;
        dfs(root, new StringBuilder());
        return helper(temp);
    }

    // dfs遍历
    private void dfs(TreeNode root, StringBuilder path) {
        path.append(root.val);
        if (root.left == null && root.right == null) {
            temp.add(new String(path));
            return;
        }
        if (root.left != null) dfs(root.left, new StringBuilder(path));
        if (root.right != null) dfs(root.right, new StringBuilder(path));
    }

    // hlper求和
    private int helper(List<String> temp) {
        int sum = 0;
        for (String s : temp) {
            sum += Integer.valueOf(s);
        }
        return sum;
    }
}
